package com.example.rdcproject.ving.notes.view.Admin;

import com.example.rdcproject.ving.notes.entity.User;
import com.example.rdcproject.ving.notes.service.ConnectionPool;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;


public class SelectAllView extends JFrame {

    ConnectionPool connectionPool = ConnectionPool.getInstance();



    public SelectAllView() {


        super("查询所有用户信息");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);

        // Create a table to show all user information
        JTable table = new JTable();
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);

        // Set the table model
        String[] columnNames = { "用户名", "用户密码盐值", "生日日期","单词记忆总数", "连续打卡天数","学习总时长","每日计划","私密状态","是否在黑名单"};
        DefaultTableModel model = new DefaultTableModel(columnNames, 0);
        table.setModel(model);

        // Load data from database and fill into table model
        List<User> userList = getAllUsers();
        for (User user : userList) {
            Object[] row = {user.getNickname(), user.getPassword(),user.getBirthdate(), user.getWordCount(),
                    user.getContinuousDays(),user.getTotalStudyTime(),user.getDailyGoal(),user.isPrivate(),user.isBlack()};
            model.addRow(row);
        }
    }

    // Get all user information from database
    private List<User> getAllUsers() {

        List<User> userList = new ArrayList<>();

        try (Connection connection = connectionPool.getConnection();
             Statement statement = connection.createStatement()) {
            String sql = "SELECT * FROM user";
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
               String nickname = resultSet.getString("user_nickname");
               String password = resultSet.getString("user_password");
               String birthdate = resultSet.getString("user_birthdate");
               int wordCount = resultSet.getInt("user_wordCount");
               int continuousDays = resultSet.getInt("user_continousDays");
               int totalStudyTime = resultSet.getInt("user_totalStudyTime");
               int dailyGoal = resultSet.getInt("user_dailyGoal");
               boolean isPrivate = resultSet.getBoolean("user_isPrivate");
               boolean isBlack = resultSet.getBoolean("user_isBlack");
                User user = new User(nickname,password,birthdate,wordCount,continuousDays,totalStudyTime,dailyGoal,isPrivate,isBlack);
                userList.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userList;
    }

}
